<?php
    include __DIR__."/config/cors.php";
    include __DIR__."/database.php";
    session_start();
    $username = $_POST['username'];
    $password = $_POST['password'];
    $passwordtoo = $_POST['passwordtoo'];
    $mail = $_POST['mail'];
    $captcha = $_POST['captcha'];
    if (strtoupper($captcha )!= strtoupper($_SESSION['captcha'])){
        echo json_encode([
            "code" => 202,
            "msg"=>"验证码不正确"
        ]);
        exit;
    }
    if ($password != $passwordtoo) {
        echo json_encode([
            "code" => 203,
            "msg"=>"两次密码不一致"
        ]);
        exit;
    }
    $db = new DB();
    $sql = "select * from user where username = '$username'";
    $data = $db->selectOne($sql);
    if (is_array($data) and count($data) > 0) {
        echo json_encode([
            "code" => 201,
            "msg"=>"注册失败"
        ]);
    }else {
        if(is_array($data) and count($data) == 0){
            $sql = "insert into user (username,password,mail,register) values ('$username','$password','$mail',NOW())";
            if ($db->insert($sql)) {
                echo json_encode([
                    "code" => 200,
                    "msg"=>"注册成功"
                ]);
            } else {
                echo json_encode([
                    "code" => 204,
                    "msg"=> "注册失败: " . $data
                ]);
            }
        }else {
            echo json_encode([
                "code" => 204,
                "msg"=> "注册失败: " . $data
              ]);
        }
    }
?>